//
//  PHAsset+iCloud.m
//  fmb
//
//  Created by ChiCo on 2017/10/30.
//  Copyright © 2017年 Linktone. All rights reserved.
//

#import "PHAsset+iCloud.h"
#import <objc/runtime.h>

static char iCloudImage;
static char requestForImage;

@implementation PHAsset (iCloud)

- (void)isCloud:(void (^)(BOOL iCloud))handle
{
    if ([self requestForImage]) {
       handle([self iCloudImage]);
    } else {
     
        [self setRequestForImage:YES];
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        [options setResizeMode:PHImageRequestOptionsResizeModeExact];
        [options setDeliveryMode:PHImageRequestOptionsDeliveryModeHighQualityFormat];
        [options setNetworkAccessAllowed:NO];
        [[PHImageManager defaultManager] requestImageForAsset:self targetSize:CGSizeMake(self.pixelWidth, self.pixelHeight) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            if (result) {
                [self setiCloudImage:NO];
            } else {
                [self setiCloudImage:YES];
            }
            handle([self iCloudImage]);
        }];
    }
  
}

- (BOOL)requestForImage
{
    return [objc_getAssociatedObject(self, &requestForImage) boolValue];
}

- (void)setRequestForImage:(BOOL)request
{
        objc_setAssociatedObject (self, &requestForImage, [NSNumber numberWithBool:request], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)iCloudImage
{
    return [objc_getAssociatedObject(self, &iCloudImage) boolValue];
}

- (void)setiCloudImage:(BOOL)iCloud
{
     objc_setAssociatedObject (self, &iCloudImage, [NSNumber numberWithBool:iCloud], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
